#include "filerequest.h"

#include <QNetworkRequest>
#include <QNetworkReply>
#include <QJsonDocument>

FileRequest::FileRequest(QObject *parent)
    : QObject{parent}
{
    manager = new QNetworkAccessManager(this);
    connect(manager,&QNetworkAccessManager::finished,this,&FileRequest::onFinished);
}

//上传文件接口
void FileRequest::uploadFile(const QByteArray &data)
{
    QNetworkRequest filerequest(QUrl("http://"+ip+":9000/file_system/upload"));
    filerequest.setRawHeader("Content-Type","application/octet-stream");
    manager->post(filerequest,data);
}

//获取文件接口
void FileRequest::getFile(const QString &avatar_url)
{
    QNetworkRequest getfilerequest(QUrl("http://"+ip+":9000/file_system/get?avatar_url=" + avatar_url));
    getfilerequest.setRawHeader("Content-Type","application/json");
    manager->get(getfilerequest);
}

QString FileRequest::getUri(const QString &url)
{
    int l1 = url.length();
    int n;
    for(int i=0;i<l1;i++){
        if(url[i]=='?'){
            n = i;
            break;
        }
    }
    int l2 = url.lastIndexOf(":") + 5;
    return url.mid(l2,n - l2);
}

void FileRequest::onFinished(QNetworkReply *reply)
{
    QString url = reply->url().toString();
    QString uri = getUri(url);
    QByteArray data = reply->readAll();
    if(uri=="/file_system/upload"){
        QJsonDocument doc = QJsonDocument::fromJson(data);
        QJsonObject obj = doc.object();
        emit uploadFinished(obj);
    }
    else if(uri=="/file_system/get"){
        emit getFinished(data);
    }
}
